<template>
  <div class="pic-lib">

     <!--按钮组-->
      <div class="Btns-ctrl-body btns-under-box">
        <!--高级搜索-->
        <SearchPublic
          :searchObj="searchObj"
          @searchParams="searchParamsFn"
        ></SearchPublic>

     <!--   <div class="search-ctrl f-l ">
          <input type="text" class="search-text" placeholder="搜索图片名称" v-model="searchStr">
          <button type="button" class="search-btn btn btn-info" @click="btnSearch(pageSize, 0)">搜索</button>
        </div>-->

        <div class="btns f-r">
          <button type="button" class="btn btn-success" @click="iconMoreSubFn">批量上传</button>
          <button type="button"
            class="btn btn-info"
            @click="btnAdd" >
            新增
          </button>
          <button type="button"
            class="btn btn-warning"
            @click="btnRevise" >
            修改
          </button>
          <button type="button"
            class="btn btn-danger"
            v-show="isDeleteBtn"
            @click="btnDelete" >
            删除
          </button>
        </div>
      </div>
      <!--按钮组闭合-->
      <div class="wrapper">
         <!-- 图片组 -->
        <div class="picture-wrapper">
          <div class="picture-item-wrapper"
            v-for="(item, index) in picArr" :key="item.id" >
            <!-- checkedPicAry通过id是否在点击数组里面来显示选中与否 -->
            <pic-box :item = item
              :class="{'no-one-row' : index > 5}"
              :checkBoxShow = checkBoxShow
              :ischeckedAry = ischeckedAry(item.id)
              @checkedAryFn = checkedAryFn ></pic-box>

          </div>
        </div>
        <!-- 图片组闭合 -->
        <!-- 分页 -->
        <pages class="pages"
          :showItem = showItem
          :allpage = allpage
          :pageSize = pageSize
          :allDataSum = allDataSum
          @current-change = currentChange >
        </pages>
        <!-- 分页闭合 -->
      </div>


      <!-- 新增修改弹框 -->
    <pic-dialog-add-revise
      :picDialogAddReviseShow = picDialogAddReviseShow
      :dialogObj="dialogObj"
      @dialogSuccessFn = dialogSuccessFn ></pic-dialog-add-revise>

    <msgDialog :dialogInit = msgDialogInit
    :dialogIsShow = msgDialogIsShow ></msgDialog>

    <isRealDialog :dialogInit = isRealDialogInit
      :dialogIsShow = isRealDialogShow
      @confirm = realDelete ></isRealDialog>

    <!--图片批量上传-->
    <IconMoreSubModal
      :IconMoreSubModalObj="IconMoreSubModalObj"
      @closeModalClose="iconMoreSubFn"
    ></IconMoreSubModal>
  </div>
</template>

<script>
import picBox from 'sudoku/atom/picBox';
import pages from 'sudoku/atom/pages';
import picDialogAddRevise from 'sudoku/atom/picDialogAddRevise';
import msgDialog from 'sudoku/atom/msgDialog';
import isRealDialog from 'sudoku/atom/isRealDialog';
import SearchPublic from "../../publicTemplate/search/SearchPublic"
import IconMoreSubModal from "./IconMoreSubModal"
import { getPic, deletePic, searchPic} from '@/api/picPool';

  export default {
    name: 'PicLib',
    props:{
      isDeleteBtn:{
        type: Boolean,
        default: true
      }
    },
    data (){
      return {
        isRealDialogShow: false,
        picArr: [],         //图片展示数据的数组
        showItem: 10,       //分页条下面item的数目
        allpage: 0,         //根据每页数据/总数据得到的总页数
        currentPage: 0,     //当前页
        pageSize: 18,       //每页数据
        allDataSum: 0,      //总数据
        checkBoxShow: true,    //图片item子组件的可选是否展现
        checkedPicAry: [],      //存放选择图片的数组
        picDialogAddReviseShow: false,       //新增修改弹框
        searchStr: '',                      //搜索输入字段
        dialogObj: {
          title: '',        //'新增图片'
          inpName: '',     //'图片名称'
          inpUrlName: '',       //'链接地址'
          btnName: '',     //'确认上传'
          isLink: false,   //不是链接页面弹框
          createUserId:"",
          updateUserId:'',
          src: '',         //static/img/shzats.png
          shade: '',
          placeholder: '',  //修改的时候传入的名称
          placeholderUrl: '',  //修改的时候传入的链接地址
          id:'',
          createTime:"",
          updateTime:'',
          storeId:''
        },
        msgDialogInit: {        //按钮操作结果消息弹框
          'title': '',
          'content': '',
          'btns': []
        },
        msgDialogIsShow: false,

        isRealDialogInit: {       //删除的时候确认弹框
          'title': '请确认删除',
          'content': ''
        },
        searchObj:{
          condition:[
            {"title":"名称","key":"name",'type':'text',"value":''},],
          htmlType:"searchDefaultPublic",
        },
        IconMoreSubModalObj:{
          isShow:false,
        },
        current: 0
      }
    },
    components: {
      picBox,
      pages,
      picDialogAddRevise,
      msgDialog,
      isRealDialog,
      SearchPublic,
      IconMoreSubModal
    },
    methods: {
      //搜索
      searchParamsFn(searchParams){
        //console.log(this.searchObj.condition);
        this.searchStr = this.searchObj.condition[0].value;
        this.btnSearch(this.pageSize,0)
      },
      getPicList (pageSize, pageCur){ //这个不用了，全部走搜索按钮的事件
        let self = this;
        let pageList = {
          page: pageCur,
          pageSize: pageSize
        }
        //发送ajax请求对应分页的数据
        getPic(pageList).then(res => {
          /**
           * res.data = {
                data: [],             //图片信息数组
                elementsSum: 155      //图片总数
             }
             res.data.data[0] = {
               createTime: "2018-07-10T17:54:01.0000000+08:00",
               createUserId: "2BCC5C5D-3B9A-4D8C-AC91-FD8CD2529B6E",
               id: "d5b3bba8-f157-4094-b492-c7e21931fedc",           //图片唯一的id
               name: "数据警规",                                      //图片的中文名字
               storeId: "340b0528-c5c6-4d12-bed8-4c483351fe9e",       //文件服务的地址
               updateTime: null,
               updateUserId: null
             }
           */
          let data = res.data.data;
          self.allpage = Math.ceil(res.data.elementsSum/self.pageSize);
          self.allDataSum = res.data.elementsSum;
          self.picArr = data;
        })
      },
      currentChange(current) {
        /**
         * current为分页组件传递过来的当前页,
         */
        // this.getPicList(this.pageSize, current)
        this.current = current - 1
        this.btnSearch(this.pageSize, current - 1)
        //分页事件发生的时候要清空保存选中的数组
        this.checkedPicAry = [];
      },
      checkedAryFn(msg) {
        /**
         *图片点击保存到checkedPicAry中
         * @param: msg.item 选中的数据
         * @param: msg.ischecked 是否选中
         */
        let item = msg.item;
        let ischecked = msg.ischecked;
        if(ischecked) {
          this.checkedPicAry.push(item);
          // 多选变成单选
          this.checkedPicAry = [this.checkedPicAry.pop()];
        }
        else {//点击取消要把其中的对应项删除
          this.checkedPicAry = this.delArray(this.checkedPicAry, item,'id')
        }

        //console.log(this.checkedPicAry)
      },
      btnSearch(pageSize, current) {
        //搜索功能
        const self = this;
        let data = {
          'name': this.searchStr,
          'page': current,
          'pageSize': pageSize
        }
        this.$axios.get(this.HOST+'/source/img/queryByName?name='
          +data.name
          +'&page='
          +data.page
          +'&pageSize='
          +data.pageSize).then( res => {
          /**
           * 应该要类似全部的接口带分页吧？
           */
          //console.log(res,'查询接口请求的数据');
          let data = res.data;
          self.allpage = Math.ceil(data.count/self.pageSize);
          self.allDataSum = data.count;
          this.picArr = data.dataList;
        })
        this.$axios.get(this.HOST+'/source/img/queryByName?name='
          +data.name
          +'&page='
          +data.page
          +'&pageSize='
          +data.pageSize)
          .then(res => {
            /**
             * 应该要类似全部的接口带分页吧？
             */
            //console.log(res,'查询接口请求的数据');
            let data = res.data;
            self.allpage = Math.ceil(data.count/self.pageSize);
            self.allDataSum = data.count;
            this.picArr = data.dataList;
          })
          .catch( err => {
            //console.log(err);
          })
        /*searchPic(data).then( res => {
          /!**
           * 应该要类似全部的接口带分页吧？
          *!/
          //console.log(res,'查询接口请求的数据');
          let data = res.data;
          self.allpage = Math.ceil(data.count/self.pageSize);
          self.allDataSum = data.count;
          this.picArr = data.dataList;
        })*/
      },
      btnAdd() {
        this.picDialogAddReviseShow = !this.picDialogAddReviseShow;
        let src='./static/img/upicon.png';
        this.dialogObj = {
          title: '新增图片',        //'新增图片'
          inpName: '图片名称',     //'图片名称'
          inpUrlName: '',       //'链接地址'
          btnName: '确认上传',     //'确认上传'
          isLink: false,   //不是链接页面弹框
          createUserId:"",
          updateUserId:'',
          src: src,         //static/img/shzats.png
          shade: '',
          placeholder: '',  //修改的时候传入的名称
          placeholderUrl: '',  //修改的时候传入的链接地址
          id:'',
          createTime:"",
          updateTime:'',
          storeId:''
        }
      },
      btnRevise() {
        if(this.checkedPicAry.length > 0 ) {//修改的选项不为空
          this.picDialogAddReviseShow = !this.picDialogAddReviseShow;
          let item = this.checkedPicAry[this.checkedPicAry.length - 1] //产品说多个就是最后一个的数据去修改
          let src = baseURL                                          //运行环境
              + 'api/jp-TIFS-FileCenter-ms/file?businessId='  //微服务地址
              + item.storeId
          this.dialogObj = {
            title: '修改图片',        //'新增图片'
            inpName: '图片名称',     //'图片名称'
            inpUrlName: '',       //'链接地址'
            btnName: '确认上传',     //'确认上传'
            isLink: false,   //不是链接页面弹框
            createUserId:"zhoupeng",     //创建者的id
            updateUserId:'zhoupeng',     //修改者的id
            src: src,         //static/img/shzats.png
            shade: '',
            placeholder: item.name,  //修改的时候传入的名称
            placeholderUrl: '',  //修改的时候传入的链接地址
            id: item.id,         //唯一id
            createTime:"",
            updateTime:'',
            storeId: item.storeId
          }
        }
        else {
          this.s_alert('请选择要修改的项!');
          // this.dialogMSG('请选择要修改的项', 1500);
        }
      },
      //删除按钮事件
      btnDelete() {
        if(this.checkedPicAry.length > 0){ // 有选择数据
          this.isRealDialogShow = !this.isRealDialogShow;
        }
        else {
          this.s_alert('请选择要删除的项');
          // this.dialogMSG('请选择要删除的项', 1500);
        }
      },
      //批量上传
      iconMoreSubFn(){
        this.IconMoreSubModalObj.isShow = !this.IconMoreSubModalObj.isShow;
        if( this.IconMoreSubModalObj.isShow === false ){
          //this.tableRowAjax()
          this.btnSearch(this.pageSize,0)
        }
      },
      realDelete() {
        let dataAry = []
        this.checkedPicAry.forEach((item) => { //删除的是id的数组
          dataAry.push(item.id)
        })
        this.$axios({
          url: this.HOST+'/source/img/delete',
          data: dataAry,
          method: 'post'
        })
          .then(res => {//删除后重新请求数据
            //清空选择数组
            this.checkedPicAry = []
            this.getPicList(this.pageSize, 1);
            //弹出操作的结果
            let msg = '删除成功!';
            this.s_alert(msg);
            // this.dialogMSG(msg, 1500);
            this.s_logwrite("宫格配置-素材图片库","删除");
          })
          .catch( err => {
            this.s_alert("删除失败！");
            //console.log(err);
          })
        // deletePic(dataAry).then(res => {//删除后重新请求数据
        //   //清空选择数组
        //   this.checkedPicAry = []
        //   this.getPicList(this.pageSize, 1);
        //   //弹出操作的结果
        //   let msg = '删除成功'
        //   this.dialogMSG(msg, 1500);
        // })
      },
      ischeckedAry(id) {
        let result = false;
        for(let i = 0; i < this.checkedPicAry.length; i++) {
          if(this.checkedPicAry[i].id == id){
            result = true;
          }
        }
        return result
      },
      dialogSuccessFn(msg) {
        //关闭弹框
        this.picDialogAddReviseShow = !this.picDialogAddReviseShow;
        //清空选择数组
        this.checkedPicAry = []
        //成功过后重新刷新页面
        // this.getPicList(this.pageSize, 1);
        this.btnSearch(this.pageSize, 0)
        //弹出操作的结果
        let str = msg + "成功!";
        this.s_alert(str);
        // this.dialogMSG(str, 1500);
      },
      dialogMSG(msg,time) {
        const self = this;
         //消息弹框
        this.msgDialogInit = {
          'title': msg,
        };
        this.msgDialogIsShow = true;
        setTimeout(function(){
          self.msgDialogIsShow = false;
        }, time)
      },
      /* * JSON数组删除对应项
        * @param: [array] json Array
        * @param: [string] 唯一的key名，根据此键名的值进行删除
        * @result: 删掉对应属性值后的数组
        */
      delArray(array, obj, key) {
        var result = [];
        for(var i = 0; i < array.length; i++){
          if( array[i][key] != obj[key] ) {
            result.push(array[i]);
          }
        }
        return result;
      }
    },
    computed: {

    },
    created() {
      // this.getPicList(this.pageSize, 1);
      this.btnSearch(this.pageSize, 0)
    }
  }
</script>

<style lang="scss" scoped>
  .pic-lib {
    width: 100%;
    height: 100%;
    .btns-under-box {
      margin-bottom: 10px;
    }
    .picture-wrapper {
      width: 100%;
      height: 100%;
      display: flex;
      flex-wrap: wrap;
      user-select:none;
      overflow: auto;
      .picture-item-wrapper {
        position: relative;
        flex: 0 0 16.6666%;
        .no-one-row {
          margin-top: 3%;
        }
      }
    }

    .wrapper {
      width: 100%;
      height: 100%;
      overflow: hidden;
      padding-bottom: 84px;
    }

  }
</style>
